<template>
  <div>
    <el-dialog
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      title="添加会员"
      width="900px"
      @close="close"
    >
      <div v-loading="dialogLoading" class="dialog-add-vip">
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          class="demo-form-inline"
          label-width="120px"
          size="small"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item prop="memberType" label="会员类型：">
                <el-select v-model="form.memberType" placeholder="请选择">
                  <el-option
                    v-for="item in memberTypeOptions"
                    :key="item"
                    :label="item"
                    :value="item"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="会员姓名：" prop="name">
                <el-input v-model.trim="form.name" placeholder="请输入" />
              </el-form-item>
              <el-form-item label="实体卡号：" prop="entityCard">
                <el-input
                  v-model.trim="form.entityCard"
                  placeholder="请输入"
                  maxlength="30"
                  show-word-limit
                />
              </el-form-item>

              <el-form-item prop="balance" label="实充余额(元)：">
                <el-input v-model.trim="form.balance" placeholder="请输入，空则无余额" maxlength="10" />
              </el-form-item>
              <el-form-item label="会员积分(个)：" prop="points">
                <el-input v-model.trim="form.points" placeholder="请输入，空则无积分" maxlength="7" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="categoryObj" label="会员卡类型：">
                <el-select v-model="form.categoryObj" value-key="id" placeholder="请选择">
                  <el-option
                    v-for="item in cardOptions"
                    :key="item.id"
                    :label="item.status?item.categoryName:item.categoryName+'(已停用)'"
                    :value="item"
                    :disabled="!item.status"
                  />
                </el-select>
              </el-form-item>
              <el-form-item prop="phone" label="会员手机：">
                <el-input v-model.trim="form.phone" maxlength="11" placeholder="请输入" />
              </el-form-item>
              <el-form-item prop="sex" label="性别：">
                <el-select v-model="form.sex" placeholder="请选择">
                  <el-option
                    v-for="item in sexOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.label"
                  />
                </el-select>
              </el-form-item>

              <el-form-item prop="giftBalance" label="赠送余额(元)：">
                <el-input v-model.trim="form.giftBalance" placeholder="请输入，空则无余额" maxlength="10" />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 更多设置 -->
          <div class="app-main-filter-collapse-box">
            <el-collapse>
              <el-collapse-item title="其它信息" name="1">
                <el-row>
                  <el-col :span="12">
                    <el-form-item prop="registerShopObj" label="所属门店名称：">
                      <el-select
                        v-model="form.registerShopObj"
                        value-key="id"
                        filterable
                        placeholder="可通过名称搜索"
                        clearable
                      >
                        <el-option
                          v-for="item in $store.state.user.allShopList"
                          :key="item.id"
                          :label="item.name"
                          :value="item"
                        />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="注册日期：" class="date" prop="registerDate">
                      <el-date-picker
                        v-model="form.registerDate"
                        :picker-options="pickerOptions"
                        type="date"
                        value-format="yyyy/MM/dd"
                        placeholder="选择日期"
                      />
                    </el-form-item>
                    <el-form-item prop="idCard" label="身份证号：">
                      <el-input v-model.trim="form.idCard" maxlength="18" show-word-limit />
                    </el-form-item>
                    <el-form-item prop="address" label="地区：">
                      <el-cascader
                        v-model="form.address"
                        :options="pcMap"
                        :props="pcMapProps"
                        placeholder="试试搜索：广州"
                        filterable
                        clearable
                      />
                    </el-form-item>

                    <el-form-item prop="work" label="行业：">
                      <el-select v-model="form.work" placeholder="请选择" clearable>
                        <el-option
                          v-for="item in workOptions"
                          :key="item"
                          :label="item"
                          :value="item"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item prop="promoterObj" label="推广员：">
                      <el-select
                        v-model="form.promoterObj"
                        value-key="phone"
                        filterable
                        placeholder="可通过姓名/手机号搜索"
                        clearable
                      >
                        <el-option
                          v-for="item in promoterOptions"
                          :key="item.phone"
                          :label="item.name+'('+item.phone+')'"
                          :value="item"
                        />
                      </el-select>
                    </el-form-item>

                    <el-form-item label="出生日期：" class="date" prop="birthday">
                      <el-date-picker
                        v-model="form.birthday"
                        :picker-options="pickerOptions"
                        type="date"
                        value-format="yyyy/MM/dd"
                        placeholder="选择日期"
                      />
                    </el-form-item>

                    <el-form-item prop="email" label="邮箱：">
                      <el-input v-model.trim="form.email" />
                    </el-form-item>
                    <el-form-item prop="education" label="学历：">
                      <el-select v-model="form.education" placeholder="请选择" clearable>
                        <el-option
                          v-for="item in educationOptions"
                          :key="item"
                          :label="item"
                          :value="item"
                        />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="爱好：" class="form_hobby">
                      <div
                        v-for="(item,index) in form.hobby"
                        :key="index"
                        class="form-hobby-val app-border-color-primary"
                      >
                        <span>{{ item }}</span>
                        <i class="el-icon-close" @click="delHobby(index)" />
                      </div>
                      <el-button
                        type="primary"
                        icon="el-icon-plus"
                        size="small"
                        circle
                        @click="addHobby"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-collapse-item>
            </el-collapse>
          </div>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" round @click="hide">取 消</el-button>
        <el-button size="small" round type="primary" @click="onSubmit('form')">保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { updateVipInfo, getAllVipCardList } from '@/api/vip'
import pcMap from '@/assets/json/pc-code.json'
import { getAllPromoters, importVipOffLine } from '@/api/vip'
// 正则匹配
import {
  validatePositiveInt,
  validateMoney,
  validateMobilePhone,
  validateEMail,
  validateIDCard,
  validateStrLen
} from '@/utils/validate.js'
export default {
  data() {
    /**
       * 表单校验方法相关
       */
    // name
    const validateName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入姓名'))
      } else if (!validateStrLen(value, 11)) {
        callback(new Error('长度不超过5个汉字或11个字符'))
      } else {
        callback()
      }
    }
    // 手机号
    const validateTelPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入手机号码'))
      } else if (!validateMobilePhone(value)) {
        callback(new Error('请输入正确手机号'))
      } else {
        callback()
      }
    }
    // 实充余额
    const validatePoints = (rule, value, callback) => {
      if (value === '') {
        callback()
      } else if (!validatePositiveInt(value, 9999999)) {
        callback(new Error('请输入正整数'))
      } else {
        callback()
      }
    }
    // 实充余额
    const validateBalance = (rule, value, callback) => {
      if (value === '') {
        callback()
      } else if (!validateMoney(value)) {
        callback(new Error('请输入正整数，正小数（小数位不超过2位）'))
      } else if (value - 999999.99 > 0) {
        callback('超过限额999999.99')
      } else {
        callback()
      }
    }
    // 赠送余额
    const validateGiftBalance = (rule, value, callback) => {
      if (value === '') {
        callback()
      } else if (!validateMoney(value)) {
        callback(new Error('请输入正整数，正小数（小数位不超过2位）'))
      } else if (value - 999999.99 > 0) {
        callback('超过限额999999.99')
      } else {
        callback()
      }
    }
    // 邮箱
    const validateEmail = (rule, value, callback) => {
      if (!value) {
        callback()
      } else if (!validateEMail(value)) {
        callback(new Error('请输入正确邮箱号'))
      } else {
        callback()
      }
    }
    // 身份证
    const validateIdCard = (rule, value, callback) => {
      if (!value) {
        callback()
      } else if (!validateIDCard(value)) {
        callback(new Error('请输入正确身份证号码'))
      } else {
        callback()
      }
    }
    return {
      /**
         * 表单校验字段相关
         */
      // 表单规则
      rules: {
        memberType: [
          {
            required: true,
            message: '请选择会员类型',
            trigger: ['change']
          }
        ],
        name: [
          {
            required: true,
            validator: validateName,
            trigger: ['blur', 'change']
          }
        ],

        categoryObj: [
          {
            required: true,
            message: '请选择会员卡',
            trigger: ['change']
          }
        ],
        phone: [
          {
            required: true,
            validator: validateTelPhone,
            trigger: ['blur', 'change']
          }
        ],
        points: [
          {
            validator: validatePoints,
            trigger: ['blur', 'change']
          }
        ],
        balance: [
          {
            validator: validateBalance,
            trigger: ['blur', 'change']
          }
        ],
        giftBalance: [
          {
            validator: validateGiftBalance,
            trigger: ['blur', 'change']
          }
        ],
        idCard: [
          {
            validator: validateIdCard,
            trigger: ['blur', 'change']
          }
        ],
        email: [
          {
            validator: validateEmail,
            trigger: ['blur', 'change']
          }
        ]
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        }
      },
      // 配置
      resolve: null,
      reject: null,
      memberTypeOptions: ['新会员', '老会员'],
      sexOptions: [
        {
          value: '1',
          label: '男'
        },
        {
          value: '0',
          label: '女'
        },
        {
          value: '-1',
          label: '未知'
        }
      ],
      workOptions: [
        'IT/互联网/通信/电子',
        '金融/投资/财会',
        '广告/媒体/出版/艺术',
        '市场/销售/客服',
        '人事/行政/管理',
        '建筑/房产/物业',
        '消费品/贸易/物流',
        '咨询/法律/认证',
        '生产/制造/营运/采购',
        '生物/制药/医疗/护理',
        '教育/培训/翻译',
        '科研/环保/休闲/其他'
      ],
      educationOptions: [
        '初中及以下',
        '高中/中技/中专',
        '大专',
        '本科',
        '硕士',
        '博士',
        '其它'
      ],
      cardOptions: [], // 会员卡选项
      promoterOptions: [], // 推广员选项
      pcMap: pcMap, // 省市选项
      pcMapProps: {
        value: 'name',
        label: 'name'
      },
      // 状态
      dialogVisible: false,
      dialogLoading: false,
      // 数据
      form: {
        memberType: '新会员',
        name: '', // 会员名
        sex: '', // 性别
        phone: '', // 手机号
        points: '', // 积分
        balance: '', // 实充余额
        giftBalance: '', // 赠送余额
        registerDate: '', // 创建时间
        birthday: '', // 生日
        idCard: '', // 身份证号
        email: '', // 邮箱
        education: '', // 学历
        work: '', // 行业
        hobby: [], // 兴趣爱好
        address: [], // 省市
        // province:"", // 省
        // city:"", // 市
        categoryObj: '', // 卡类型对象
        // category: "",
        // categoryName:"",
        registerShopObj: '', // 注册门店对象
        // shopId: "",
        // registerShop:"",
        promoterObj: '' // 推广员对象
        // promoterPhone: ""
        // promoterCode: "",
        // promoterName: "",
      }
    }
  },
  mounted() {},
  methods: {
    open() {
      this.show()
      return new Promise((resolve, reject) => {
        this.resolve = resolve
        this.reject = reject
      })
    },

    show() {
      this.getCardList()
      this.getPromoterList()
      this.dialogVisible = true
    },

    hide() {
      this.resolve = null
      this.reject = null
      this.dialogVisible = false
    },

    close() {
      this.dialogLoading = false
      this.$refs.form.resetFields()
      this.form.hobby = []
    },

    /**
       * 获取数据
       */
    // 获取会员卡列表
    getCardList() {
      getAllVipCardList().then((res) => {
        this.cardOptions = res.data
      })
    },

    // 获取所有推广员数据
    getPromoterList() {
      getAllPromoters().then((res) => {
        this.promoterOptions = res.data || []
      })
    },

    onSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const params = Object.assign({}, this.form)
          // 格式化会员卡
          params.category = params.categoryObj.id
          params.categoryName = params.categoryObj.categoryName
          delete params.categoryObj

          // 格式化推广员
          if (params.promoterObj) {
            params.promoterCode = params.promoterObj.phone
            params.promoterName = params.promoterObj.name
            params.promoterPhone = params.promoterObj.serialCode
            delete params.promoterObj
          }

          // 格式化注册门店
          if (params.registerShopObj) {
            params.shopId = params.registerShopObj.id
            params.registerShop = params.registerShopObj.name
            delete params.registerShopObj
          }

          // 格式化地区
          if (params.address.length !== 0) {
            params.province = params.address[0]
            params.city = params.address[1]
            delete params.address
          }

          // 格式化兴趣
          params.hobby = params.hobby.join(',')
          // 清除多余字段
          for (const key in params) {
            if (params[key] === '') {
              delete params[key]
            }
          }

          this.dialogLoading = true
          importVipOffLine(params)
            .then((res) => {
              this.dialogLoading = false
              // 成功
              this.$notify({
                title: '成功',
                message: '录入成功',
                type: 'success',
                duration: 2000,
                offset: 40
              })
              // 新增成功则重新获取列表数据
              this.resolve && this.resolve()
              this.hide()
            })
            .catch((err) => {
              this.dialogLoading = false
            })
        }
      })
    },

    // 新增爱好
    addHobby() {
      this.$prompt('', '请输入爱好', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: this.validateHobby
      }).then(({ value }) => {
        this.form.hobby.push(value)
        this.form.hobby = [...new Set(this.form.hobby)]
      })
    },
    // 校验兴趣爱好
    validateHobby(value) {
      if (value === '') {
        return '请输入兴趣爱好'
      } else if (!validateStrLen(value, 20)) {
        return '长度不超过10个汉字或20个字符'
      }
    },

    // 删除爱好
    delHobby(index) {
      this.form.hobby.splice(index, 1)
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  .dialog-add-vip {
    .el-date-editor .el-input {
      width: 100%;
    }
    .form-hobby-val {
      display: inline-block;
      height: 30px;
      padding: 0 5px 0 10px;
      margin-right: 10px;
      border-width: 1px;
      border-style: solid;
      border-radius: 5px;
      line-height: 30px;
      font-size: 14px;
      color: $dark-font-color;
    }
    .el-date-editor,
    .el-cascader,
    .el-select {
      width: 100%;
    }
    .el-icon-close {
      cursor: pointer;
    }
  }
</style>
